<template>
  <div class="card mt-4 task-card">
    <div class="card-header d-flex justify-content-between align-items-center">
      <div>
        <i class="bi bi-list-check"></i> 任务列表
      </div>
      <button 
        class="btn btn-sm btn-outline-danger" 
        @click="confirmClearAllTasks"
        title="清除所有任务"
      >
        <i class="bi bi-trash"></i> 清除所有
      </button>
    </div>
    <div class="card-body task-list">
      <div class="empty-state" v-if="taskStore.sortedTasks.length === 0">
        <i class="bi bi-inbox"></i>
        <p>暂无任务</p>
      </div>
      <div class="table-responsive" v-else>
        <table class="table table-hover">
          <thead class="table-light">
            <tr>
              <th width="40"></th>
              <th>文件名</th>
              <th>开始时间</th>
              <th>结束时间</th>
              <th>状态</th>
              <th>进度</th>
              <th width="80">成功</th>
              <th width="80">失败</th>
              <th width="180">操作</th>
            </tr>
          </thead>
          <tbody>
            <template v-for="task in taskStore.sortedTasks" :key="task.task_id">
              <tr 
                :class="{'table-active': task.task_id === selectedTaskId}" 
                class="task-row"
                @click="selectTask(task.task_id)"
              >
                <td>
                  <button 
                    class="btn btn-sm btn-outline-primary expand-btn" 
                    @click.stop="toggleDetails(task.task_id)"
                  >
                    <i :class="`bi ${isExpanded(task.task_id) ? 'bi-chevron-up' : 'bi-chevron-down'}`"></i>
                  </button>
                </td>
                <td>{{ task.file_name || '未知文件' }}</td>
                <td>{{ formatDateTime(task.start_time) }}</td>
                <td>{{ task.end_time ? formatDateTime(task.end_time) : '-' }}</td>
                <td>
                  <span 
                    :class="`badge ${getStatusBadgeClass(task.status)}`"
                  >
                    {{ getStatusText(task.status) }}
                  </span>
                </td>
                <td>
                  <small class="text-muted">
                    {{ task.completed_dois }}/{{ task.total_dois || 0 }}
                  </small>
                </td>
                <td>
                  <span class="badge bg-success">{{ task.success_dois || 0 }}</span>
                </td>
                <td>
                  <span class="badge bg-danger">{{ task.failed_dois || 0 }}</span>
                </td>
                <td>
                  <button 
                    class="btn btn-sm btn-outline-danger" 
                    @click.stop="confirmDeleteTask(task.task_id)"
                    title="删除任务"
                  >
                    <i class="bi bi-trash"></i>
                  </button>
                  <button 
                    v-if="task.status === 'completed' && task.success_dois > 0"
                    @click.stop="handleDownloadTaskPdfs(task.task_id)"
                    class="btn btn-sm btn-outline-primary ms-1"
                    title="下载所有PDF文件"
                  >
                    <i class="bi bi-download"></i>
                  </button>
                  <!-- 添加导出Excel按钮 -->
                  <button 
                    v-if="task.status === 'completed'"
                    @click.stop="handleExportTaskResults(task.task_id)"
                    class="btn btn-sm btn-outline-success ms-1"
                    title="导出Excel"
                  >
                    <i class="bi bi-file-earmark-spreadsheet"></i>
                  </button>
                  <!-- 添加追加到源文件按钮 -->
                  <button 
                    v-if="task.status === 'completed' && task.file_name && (task.file_name.endsWith('.xlsx') || task.file_name.endsWith('.xls'))"
                    @click.stop="handleExportToSourceFile(task.task_id)"
                    class="btn btn-sm btn-outline-info ms-1"
                    title="追加到源文件"
                  >
                    <i class="bi bi-file-earmark-plus"></i>
                  </button>
                </td>
              </tr>
              <tr v-show="isExpanded(task.task_id)" class="doi-details-row">
                <td colspan="9">
                  <DoiDetails :taskId="task.task_id" />
                </td>
              </tr>
            </template>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue';
import { useTaskStore } from '@/stores/taskStore';
import DoiDetails from './DoiDetails.vue';
// 在文件顶部导入部分添加
import { deleteTask, deleteAllTasks, downloadTaskPdfs, exportTaskResults, exportToSourceFile } from '@/services/api';

const taskStore = useTaskStore();
// 从localStorage加载展开状态，如果没有则使用空集合
const expandedTasks = ref<Set<string>>(new Set());
const selectedTaskId = ref<string | null>(null);

// 从localStorage加载展开状态
onMounted(() => {
  try {
    const savedExpandedTasks = localStorage.getItem('expandedTasks');
    if (savedExpandedTasks) {
      expandedTasks.value = new Set(JSON.parse(savedExpandedTasks));
    }
  } catch (error) {
    console.error('Failed to load expanded tasks from localStorage:', error);
  }
});

// 监听展开状态变化，保存到localStorage
watch(expandedTasks.value, () => {
  try {
    localStorage.setItem('expandedTasks', JSON.stringify([...expandedTasks.value]));
  } catch (error) {
    console.error('Failed to save expanded tasks to localStorage:', error);
  }
}, { deep: true });

// 方法
function toggleDetails(taskId: string) {
  if (expandedTasks.value.has(taskId)) {
    expandedTasks.value.delete(taskId);
  } else {
    expandedTasks.value.add(taskId);
  }
  // 手动触发保存到localStorage
  localStorage.setItem('expandedTasks', JSON.stringify([...expandedTasks.value]));
}

function isExpanded(taskId: string): boolean {
  return expandedTasks.value.has(taskId);
}

function selectTask(taskId: string) {
  selectedTaskId.value = taskId;
  taskStore.setSelectedTaskId(taskId);
}

async function confirmClearAllTasks() {
  const taskTypeText = taskStore.currentTaskType === 'DOI' ? 'Sci-Hub' : '江苏省审查报告';
  if (confirm(`确定要清除所有${taskTypeText}任务记录吗？这将同时删除服务器上的任务记录。`)) {
    try {
      // 调用API删除服务器上的所有任务，传入当前任务类型
      await deleteAllTasks(taskStore.clientId, taskStore.currentTaskType);
      // 清除本地存储中的任务
      taskStore.clearAllTasks();
      expandedTasks.value.clear();
      selectedTaskId.value = null;
    } catch (error) {
      console.error('删除所有任务失败:', error);
      alert('删除服务器任务失败，但本地记录已清除');
      // 即使服务器删除失败，也清除本地记录
      taskStore.clearAllTasks();
      expandedTasks.value.clear();
      selectedTaskId.value = null;
    }
  }
}

async function confirmDeleteTask(taskId: string) {
  if (confirm(`确定要删除任务 ${taskId.substring(0, 8)}... 吗？`)) {
    try {
      // 调用API删除任务
      await deleteTask(taskId);
      // 从本地存储中删除任务
      taskStore.deleteTask(taskId);
      // 如果删除的是当前选中的任务，清除选中状态
      if (selectedTaskId.value === taskId) {
        selectedTaskId.value = null;
      }
      // 从展开列表中移除
      if (expandedTasks.value.has(taskId)) {
        expandedTasks.value.delete(taskId);
        localStorage.setItem('expandedTasks', JSON.stringify([...expandedTasks.value]));
      }
      // 显示成功通知
      taskStore.addNotification('success', '删除成功', `任务 ${taskId.substring(0, 8)}... 已成功删除`);
    } catch (error) {
      console.error('删除任务失败:', error);
      taskStore.addNotification('error', '删除失败', `任务 ${taskId.substring(0, 8)}... 删除失败`);
    }
  }
}

function getStatusBadgeClass(status: string): string {
  switch (status) {
    case 'completed': return 'bg-success';
    case 'failed': return 'bg-danger';
    case 'processing': return 'bg-warning text-dark';
    default: return 'bg-secondary';
  }
}

 
function getStatusText(status: string): string {
  switch (status) {
    case 'completed': return '已完成';
    case 'failed': return '失败';
    case 'processing': return '处理中';
    default: return '等待中';
  }
}

function formatDateTime(dateStr: string): string {
  if (!dateStr) return '-';
  
  const date = new Date(dateStr);
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}`;
}

// 添加下载PDF文件的方法
function handleDownloadTaskPdfs(taskId: string) {
  try {
    // 调用API下载PDF文件
    downloadTaskPdfs(taskId);
  } catch (error) {
    console.error('下载PDF文件失败:', error);
    taskStore.addNotification('error', '下载失败', `任务 ${taskId.substring(0, 8)}... PDF文件下载失败`);
  }
}

// 添加导出Excel文件的方法
function handleExportTaskResults(taskId: string) {
  try {
    // 调用API导出Excel文件
    exportTaskResults(taskId);
  } catch (error) {
    console.error('导出Excel文件失败:', error);
    taskStore.addNotification('error', '导出失败', `任务 ${taskId.substring(0, 8)}... Excel文件导出失败`);
  }
}

// 添加追加到源文件的方法
function handleExportToSourceFile(taskId: string) {
  try {
    // 调用API追加到源文件
    exportToSourceFile(taskId);
  } catch (error) {
    console.error('追加到源文件失败:', error);
    taskStore.addNotification('error', '追加失败', `任务 ${taskId.substring(0, 8)}... 追加到源文件失败`);
  }
}
</script>

<style scoped>
.task-card {
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  border: none;
  border-radius: 8px;
}

.card-header {
  background-color: #f8f9fa;
  border-bottom: 1px solid rgba(0, 0, 0, 0.125);
  padding: 12px 16px;
}

.empty-state {
  text-align: center;
  padding: 40px;
  color: #aaa;
  background-color: #f9f9f9;
  border-radius: 8px;
  margin: 10px 0;
}

.empty-state i {
  font-size: 3rem;
  margin-bottom: 15px;
  color: #ccc;
}

.task-row {
  cursor: pointer;
  transition: background-color 0.2s;
}

.task-row:hover {
  background-color: rgba(0, 123, 255, 0.05);
}

.doi-details-row {
  background-color: #f8f9fa;
}

.expand-btn {
  width: 32px;
  height: 32px;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
}

.progress {
  height: 10px !important;
  margin-bottom: 5px;
  border-radius: 5px;
}

.badge {
  font-weight: 500;
  padding: 5px 8px;
}

thead {
  position: sticky;
  top: 0;
  z-index: 1;
}
</style>